import { routerRedux } from 'dva/router';
import queryString from 'query-string';
import { getListData, addForm,/* delForm, */ copyForm, updateStatus, isExternalForm, getExternalFormDetail } from "../server/formConfigureApi";
import { getFormDetail } from "../../formbuilder/server/formBuilderApi";

const initData = {
  listData: [],
  totalCount: 0,
};

export default {
  namespace: "FormConfigure",
  state: {
    ...initData,
  },

  effects: {
    *getListData({ payload }, { call, put }) {
      const resData = yield call(getListData, payload);
      const { datas = [], totalCount = 0 } = resData || {};
      yield put({ type: "get/listData", payload: datas || [], totalCount });
    },
    *addOrCopyForm({ payload, actionType }, { call, put }) {
      let callFn = addForm;
      if (actionType === 'copy') {
        callFn = copyForm;
      }
      const { errCode, errMsg, errortext, datas } = yield call(callFn, payload);
      if (errCode === 0) {
        const id = datas;
        yield put(routerRedux.push({
          pathname: '/flowmanage/formbuilder',
          search: queryString.stringify({
            formId: id,
          }),
          state: { isAdd: true },
        }));
      }
      return { errCode, errMsg: errMsg || errortext, datas }
    },
    *delForm({ payload }, { call }) {
      // const { errCode, errMsg, errortext } = yield call(delForm, payload);
      const { formId } = payload;
      const { errCode, errMsg, errortext } = yield call(updateStatus, { formId, status: 3 });
      return { errCode, errMsg: errMsg || errortext }
    },
    *publishForm({ payload }, { call }) {
      const { formId } = payload;
      const { errCode, errMsg, errortext } = yield call(updateStatus, { formId, status: 1 });
      return { errCode, errMsg: errMsg || errortext }
    },
    *stopForm({ payload }, { call }) {
      const { formId } = payload;
      const { errCode, errMsg, errortext } = yield call(updateStatus, { formId, status: 2 } );
      return { errCode, errMsg: errMsg || errortext }
    },
    *getFormDetail({ payload }, { call }) {
      const resData = yield call(getFormDetail, payload);
      const { errCode, errMsg, datas = {}, errortext } = resData || {};
      return { errCode, errMsg: errMsg || errortext, datas };
    },
    *isExternalForm({ payload }, { call }) {
      const resData = yield call(isExternalForm, payload);
      const { errCode, errMsg, datas = {}, errortext } = resData || {};
      return { errCode, errMsg: errortext || errMsg, datas };
    },
    *getExternalFormDetail({ payload }, { call }) {
      const resData = yield call(getExternalFormDetail, payload);
      const { errCode, errMsg, datas = {}, errortext } = resData || {};
      return { errCode, errMsg: errMsg || errortext, datas };
    },
  },
  reducers: {
    "get/listData": (state, { payload, totalCount }) => ({
      ...state,
      listData: payload,
      totalCount,
    }),
    clearData: () => ({ ...initData }),
  },
};
